from django.shortcuts import render,redirect
from django.contrib.auth.models import User
from django.contrib.auth import login, logout, authenticate
from .models import Article,Category,Tags
from django.http import HttpResponse
import json

# 首页
def index(request):
    articles = Article.objects.all()
    categorys=Category.objects.all()
    tags = Tags.objects.all()
    return render(request,"index.html",{"articles":articles,"categorys":categorys,"tags":tags})

# 欢迎页
def welcome(request):
    return render(request, "welcome.html")

# 发布文章
def publish(request):
    categorys = Category.objects.all()
    tags = Tags.objects.all()
    return render(request, "publish.html",{"categorys":categorys,"tags":tags})

# 添加Article
def addArticle(request):
    title = request.POST["title"]
    intro = request.POST["intro"]
    categoryId = request.POST["category"]
    tagsId = request.POST["tags"]
    body = request.POST["body"]

    category=Category.objects.get(id=categoryId)
    tags=Tags.objects.get(id=tagsId)
    article =Article()
    article.title=title
    article.intro=intro
    article.category=category
    article.tags=tags
    article.body=body
    article.user=request.user
    article.save()
    return render(request, "publish.html", {"info": "ok"})

# 根据id查询
def getArticleById(request,id):
    article=Article.objects.get(id=id)
    articles = Article.objects.all()
    categorys = Category.objects.all()
    tags = Tags.objects.all()
    return render(request, "details.html",{"article":article,"articles":articles,"categorys":categorys,"tags":tags})

# 编辑Article
def editArticle(request,id):
    article=Article.objects.get(id=id)
    articles = Article.objects.all()
    categorys = Category.objects.all()
    tags = Tags.objects.all()
    return render(request, "edit.html",{"article":article,"articles":articles,"categorys":categorys,"tags":tags})

# 更新Article
def updateArticle(request):
    id = request.POST["id"]
    title = request.POST["title"]
    intro = request.POST["intro"]
    body = request.POST["body"]
    article = Article.objects.get(id=id)
    article.title = title
    article.intro = intro
    article.body = body
    article.save()
    return render(request, "edit.html", {"info": "ok"})

# 根据分类查询
def getArticleListBycategory(request,id):
    articles = Article.objects.filter(category=id)
    category = Category.objects.get(id=id)
    categorys = Category.objects.all()
    tags = Tags.objects.all()
    return render(request, "list.html",{"articles":articles,
    "categorys":categorys,"tags":tags,"category":category})

# 根据标题查询
def getArticleByTitle(request):
    keyboard = request.POST["keyboard"]
    article = Article.objects.filter(title=keyboard)
    articles = Article.objects.all()
    categorys = Category.objects.all()
    tags = Tags.objects.all()
    return render(request, "search.html",{"articles":articles,"article":article,"categorys":categorys,"tags":tags})

# 根据标签查询
def getArticleByTag(request,id):
    articles = Article.objects.filter(tags=id)
    category = Category.objects.get(id=id)
    categorys = Category.objects.all()
    tags = Tags.objects.all()
    return render(request, "list.html", {"articles": articles,
                "categorys": categorys, "tags": tags, "category":category,"categorys": categorys})
# 注册页面
def register(request):
    return render(request, "register.html")

# 后台管理
def manage(request):
    articles = Article.objects.all()
    categorys = Category.objects.all()
    return render(request, "manage.html",{"categorys":categorys,"articles":articles})

# 文章列表
def articleList(request):
    return render(request, "articleList.html")

# 分类列表
def categoryList(request):
    return render(request, "categoryList.html")

# 获取分类列表
def getCategoryList(request):
    categorys = Category.objects.all()
    lis = []
    for i in categorys:
        dict = {}
        dict['id'] = i.id
        dict['categoryName'] = i.categoryName
        lis.append(dict)
    Result = {"code": 0, "msg": "", "data": lis}
    return HttpResponse(json.dumps(Result), content_type="application/json")

# 获取Article
def getArticle(request):
    articles = Article.objects.all()
    lis = []
    for i in articles:
        dict = {}
        dict['id'] = i.id
        dict['title'] = i.title
        dict['category'] = i.category.categoryName
        dict['tags'] = i.tags.tagsName
        lis.append(dict)
    Result = {"code": 0, "msg": "","data": lis}
    return HttpResponse(json.dumps(Result), content_type="application/json")

# 用户登录
def login(request):
    if request.method == 'POST':
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        if User.objects.filter(username=username):
            user = authenticate(username=username, password=password)
            if user:
                request.session['username'] = username
                return redirect('/manage/')
            else:
                tips = '账号密码错误，请重新输入'
        else:
            tips = '用户不存在，请注册'
    return render(request, 'login.html', locals())

# 添加分类
def addCategory(request):
    if request.method == 'POST':
        categoryName = request.POST.get('categoryName')
        category=Category()
        category.categoryName=categoryName
        category.save()
        return render(request, "addCategory.html", {"info": "ok"})
    return render(request, 'addCategory.html')

# 编辑分类
def editCategory(request,id):
    category = Category.objects.get(id=id)
    return render(request, 'editCategory.html',{"category":category})

# 更新分类
def updateCategory(request):
    id=request.POST.get('id')
    categoryName=request.POST.get('categoryName')
    print("id="+id+",categoryName="+categoryName)
    category = Category.objects.get(id=id)
    category.categoryName=categoryName
    category.save()
    return render(request, 'editCategory.html', {"info": "ok"})

# 删除分类
def delete(request,id):
    print("id="+id)
    Category.objects.get(id=id).delete()
    return redirect('/categoryList/')